import { ref, reactive, nextTick } from 'vue'
import { DialogConfig } from '@/types/config'
import { DictItem } from '@/types/dict'
import { FormInstance, FormRules } from 'element-plus'

/**
 * 字典表单管理 Hook
 * 专门管理字典的表单配置、验证规则等
 */
export function useDictForm() {
  const refForm = ref<FormInstance>()
  /**字典弹框配置项 */
  const dialogConfig = reactive<Partial<DialogConfig>>({
    dialogTitle: '默认标题',
    dialogWidth: '40%',
    dialogTop: '5vh',
  })

  /**字典表单数据 */
  const DictForm = ref<DictItem>({
    id: '',
    pid: '',
    dictCode: '',
    name: '',
    desc: '',
    type: '',
    value: null,
  })

  /**字典校验规则 */
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
    dictCode: [
      { required: true, message: '请输入字典编码', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9_]+$/,
        message: '编码只能包含数字、字母和下划线',
        trigger: 'blur',
      },
    ],
    type: [{ required: true, message: '请选择字典类型', trigger: 'change' }],
    value: [
      { required: true, message: '请输入字典值', trigger: 'blur' },
      {
        pattern: /^\d+$/,
        message: '字典值必须为数字',
        trigger: 'blur',
      },
    ],
  })

  /**重置表单 */
  const resetForm = () => {
    nextTick(() => {
      refForm.value?.resetFields()
      DictForm.value.id = '' // 重置ID，因为id没有在form表单中，无法通过resetFields重置
      console.log('重置表单数据:', DictForm.value)
    })
  }
  // 设置添加模式
  const setAddMode = () => {
    dialogConfig.dialogTitle = '添加字典'
    resetForm()
  }

  // 设置编辑模式
  const setEditMode = (item: any) => {
    dialogConfig.dialogTitle = '编辑字典'
    resetForm()
    nextTick(() => {
      Object.assign(DictForm.value, item)
    })
  }

  return {
    dialogConfig,
    DictForm,
    rules,
    resetForm,
    setAddMode,
    setEditMode,
    refForm,
  }
}
